package com.dianrui.qiyouriding.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.AuthTask;
import com.blankj.utilcode.util.SPUtils;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.alipay.AuthResult;
import com.dianrui.qiyouriding.bean.WxCode;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.SharedUtil;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.dianrui.qiyouriding.view.VerificationCodeInput;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 收益提现
 */
@SuppressWarnings("ALL")
public class WithDrawPutForwardActivity extends BaseActivity {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.cb_zfb)
    CheckBox cbZfb;
    @BindView(R.id.cb_wx)
    CheckBox cbWx;
    @BindView(R.id.top_right)
    TextView topRight;
    @BindView(R.id.with_moneys)
    EditText withMoneys;
    @BindView(R.id.show_balance)
    TextView showBalance;
    @BindView(R.id.withdraw)
    Button withdraw;
    @BindView(R.id.right_img)
    ImageView rightImg;
    private IWXAPI wxApi;

    @Override
    public int getContentViewId() {
        return R.layout.act_withdraw_put_forward;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        customInit(true, R.color.main_color);
        title.setText(getString(R.string.withdrawputforwordtitle));
        rightImg.setImageResource(R.mipmap.more);
        rightImg.setVisibility(View.VISIBLE);
        getBalanaceInfo();
        getContractMemberInfo();
        withMoneys.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    withdraw.setBackgroundResource(R.drawable.green_gradient);
                } else {
                    withdraw.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });

    }

    //获取余额（当前余额和已提现）
    private void getBalanaceInfo() {
        OkHttpRequest.getInstance().postWithMemberToken(Url.WITHDRAWBALANCE, "",  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                showBalance.setText(jsonObject.optJSONObject("data").optString("balance"));//已提现
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                SPUtils.getInstance().clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                SharedUtil.setToken("");
                                JumpKillActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    private void getContractMemberInfo() {
        OkHttpRequest.getInstance().postWithMemberToken(Url.CONTRACT_MEMBER, "",  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                SPUtils.getInstance().put("mobiles", jsonObject.optJSONObject("data").optString("mobile"));
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                SPUtils.getInstance().clear();
                                SharedUtil.setToken("");
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpKillActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });


    }

    @Override
    public void initData() {
    }


    @OnClick({R.id.back, R.id.cb_zfb, R.id.click_zfb, R.id.cb_wx, R.id.click_wx, R.id.withdraw, R.id.all_withdraw, R.id.right_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.cb_zfb:
                cbWx.setChecked(false);
                cbZfb.setChecked(true);
                break;
            case R.id.click_zfb:
                cbWx.setChecked(false);
                cbZfb.setChecked(true);
                break;
            case R.id.cb_wx:
                cbWx.setChecked(true);
                cbZfb.setChecked(false);
                break;
            case R.id.click_wx:
                cbWx.setChecked(true);
                cbZfb.setChecked(false);
                break;
            case R.id.withdraw:
                final String money = withMoneys.getText().toString().trim();
                if (StringUtils.isEmpty(money)) {
                    ToastUtil.showToast(getString(R.string.please_enter_the_withdrawal_amount));
                    return;
                }
                if (StringUtils.toFloat(money) < 1) {
                    ToastUtil.showToast(getString(R.string.balance_cannot_be_zero));
                    return;
                }
                if (cbZfb.isChecked()) {
                    getZfbAuth();
                } else if (cbWx.isChecked()) {
                    wxApi = WXAPIFactory.createWXAPI(WithDrawPutForwardActivity.this, Constant.WXAppID, true);
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "wx_login_duzun";
                    wxApi.sendReq(req);
                }
                break;
            case R.id.all_withdraw:
                withMoneys.setText(showBalance.getText().toString());
                break;
            case R.id.right_img:
                JumpActivitys(WithDrawRecordListActivity.class);
                break;

            default:
                break;
        }
    }

    private void getSms(final String authcode) {
        showLoadingDialog(getString(R.string.send_sms));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("account", SPUtils.getInstance().getString("mobiles"));
        jsonObject.addProperty("type", 5);//1登录/注册，2修改绑定手机，3代理商获取验证码，4申请合同签约，5提现验证码
        OkHttpRequest.getInstance().postRequests(Url.GETCODE, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                showSmsZfbDialog(authcode);
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //显示
    private void showSmsZfbDialog(final String authcode) {
        AlertDialog.Builder builder = new AlertDialog.Builder(WithDrawPutForwardActivity.this, R.style.RcDialogs);
        View view1 = LayoutInflater.from(WithDrawPutForwardActivity.this).inflate(R.layout.start_auth_dialog, null);
        final AlertDialog dialog = builder.create();
        dialog.setView(view1);
        dialog.show();
        TextView showMoney = view1.findViewById(R.id.show_money);
        showMoney.setText(withMoneys.getText().toString());
        final VerificationCodeInput verificationCodeInput = view1.findViewById(R.id.verificationCodeInput);
        verificationCodeInput.setOnCompleteListener(new VerificationCodeInput.Listener() {
            @Override
            public void onComplete(String content) {
                if (content.length() == 6) {
                    dialog.cancel();
                    submitWithDrawZfb("2", authcode, verificationCodeInput.getContent());
                }
            }
        });
        ImageView imageView = view1.findViewById(R.id.close);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });
    }


    private void getSmsWx(final String code) {
        showLoadingDialog(getString(R.string.send_sms));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("account", SPUtils.getInstance().getString("mobiles"));//手机号
        jsonObject.addProperty("type", 5);//验证类型：1登录/注册，2修改绑定手机，3代理商获取验证码，4申请合同签约，5提现验证码
        OkHttpRequest.getInstance().postRequests(Url.GETCODE, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                showSmsWxDialog(code);
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    private void showSmsWxDialog(final String code) {
        AlertDialog.Builder builder = new AlertDialog.Builder(WithDrawPutForwardActivity.this, R.style.RcDialogs);
        View view1 = LayoutInflater.from(WithDrawPutForwardActivity.this).inflate(R.layout.start_auth_dialog, null);
        final AlertDialog dialog = builder.create();
        dialog.setView(view1);
        dialog.show();
        TextView showMoney = view1.findViewById(R.id.show_money);
        showMoney.setText(withMoneys.getText().toString());
        final VerificationCodeInput verificationCodeInput = view1.findViewById(R.id.verificationCodeInput);
        verificationCodeInput.setOnCompleteListener(new VerificationCodeInput.Listener() {
            @Override
            public void onComplete(String content) {
                if (content.length() == 6) {
                    dialog.dismiss();
                    submitWithDrawWx("1", code, verificationCodeInput.getContent());
                }
            }
        });
        ImageView imageView = view1.findViewById(R.id.close);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.cancel();
            }
        });
    }

    //获取支付宝授权
    private void getZfbAuth() {
        OkHttpRequest.getInstance().postWithMemberToken(Url.ZFBAUTH, "", new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject &&!isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                getAuthResultFromAuthInfo(jsonObject.optJSONObject("data").optString("contents"));
                            } else {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    //微信授权后传递code并发送请求
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WxCode wxCode) {
        getSmsWx(wxCode.code);
    }

    //TODO
    //支付宝授权
    private void getAuthResultFromAuthInfo(final String alipaySdkAuthInfo) {
        Runnable authRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(WithDrawPutForwardActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(alipaySdkAuthInfo, true);
                Log.e("授权结果:", result + "");
                Message msg = new Message();
                msg.what = 2;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    //支付宝授权回调
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code为“200”则代表授权成功，
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取authcode
                        Log.e("返回code:", authResult.getAuthCode());
                        ToastUtil.showToast("授权成功");
                        getSms(authResult.getAuthCode());//授权成功后支付宝返回一个认证码
                    } else {
                        if (TextUtils.isEmpty(authResult.getAuthCode())) {
                            ToastUtil.showToast(authResult.getResult());
                        } else {
                            ToastUtil.showToast(authResult.getResult());
                        }
                    }
                    break;
                default:
                    break;

            }
        }
    };

    //用微信提现
    private void submitWithDrawWx(String paymentMode, String code, String verifyCode) {
        showLoadingDialog(getString(R.string.please_wait_while_we_withdraw));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("money", withMoneys.getText().toString().trim());
        jsonObject.addProperty("payment_mode", paymentMode);
        jsonObject.addProperty("code", code);//微信授权信息
        jsonObject.addProperty("verify_code", verifyCode);
        OkHttpRequest.getInstance().postWithMemberToken(Url.WITHDRAWSUBMIT, jsonObject.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject != null && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                finish();
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (JSONException e) {
                        dismissLoadingDialog();
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    //用支付宝提现
    private void submitWithDrawZfb(String paymentMode, String payeeAccount, String verifyCode) {
        showLoadingDialog(getString(R.string.please_wait_while_we_withdraw));
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("money", withMoneys.getText().toString().trim());
        jsonObject.addProperty("payment_mode", paymentMode);
        jsonObject.addProperty("payee_account", payeeAccount);//支付宝授权信息
        jsonObject.addProperty("verify_code", verifyCode);
        OkHttpRequest.getInstance().postWithMemberToken(Url.WITHDRAWSUBMIT, jsonObject.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject != null && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                finish();
                            } else {
                                dismissLoadingDialog();
                                ToastUtil.showToast(jsonObject.optString("message"));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                dismissLoadingDialog();
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}
